/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.utbm.tx52.stamp.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import fr.utbm.tx52.stamp.R;
import fr.utbm.tx52.stamp.logic.Contact;
import fr.utbm.tx52.stamp.ui.activity.Main;

/**
 * Fragment used to display a contact in the AddressBook fragment
 *
 * @author GREA Antoine
 * @author TISSERAND Geoffrey
 */
public class ContactItem extends Fragment
{

	private Contact contact;
	private LinearLayout linearLayout;

	public Contact getContact()
	{
		return contact;
	}

	public LinearLayout getLinearLayout()
	{
		return linearLayout;
	}
	private QuickContactBadge quickContactBadge;
	private TextView name;
	private TextView phone;
	private Activity activity;

	public ContactItem(Activity activity)
	{
		this.activity = activity;
	}

	protected Activity getActivity_()
	{
		return (getActivity() != null) ? getActivity() : activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState)
	{
		// Inflate the layout for this fragment
		linearLayout = (LinearLayout) inflater.inflate(R.layout.contact, container, false);
		quickContactBadge = (QuickContactBadge) linearLayout.findViewById(R.id.contact_badge);
		quickContactBadge.setImageToDefault();
		quickContactBadge.setClickable(false);
		linearLayout.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				getActivity_().startActivityForResult(intentContact, Main.PICK_MY_CONTACT);
			}
		});

		name = (TextView) linearLayout.findViewById(R.id.contact_name);
		name.setText(getActivity_().getResources().getString(R.string.me));

		phone = (TextView) linearLayout.findViewById(R.id.contact_phone);
		phone.setText(getActivity_().getResources().getString(R.string.click_to_edit));

		return linearLayout;
	}

	public void setContact(Contact contact)
	{
		this.contact = contact;
	}

	public void drawContact()
	{
		if (contact != null && contact.getID() != null
			&& quickContactBadge != null
			&& name != null
			&& phone != null
			&& linearLayout != null)
		{
			linearLayout.setOnClickListener(null);
			quickContactBadge.assignContactUri(contact.getUri());
			quickContactBadge.setClickable(true);
			// TODO do it dpi dependent
			Bitmap image = Bitmap.createScaledBitmap(contact.getBitmap(), 96, 96, true);
			quickContactBadge.setImageBitmap(image);
			name.setText(contact.getName());
			phone.setText(contact.getPhoneNumber());
		}
	}
}
